﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Data.Common;
using Data.Enum;
using Data.Model;
using DataAccess.SystemManage;
using Ninject;
using WinForm.Helper;

namespace WinForm.Dialog
{
    public partial class EditPR : Form
    {
        private static readonly IKernel Kernel = new StandardKernel(new DbModule());
        private readonly ISysPrivilege _sysPrivilege = Kernel.Get<ISysPrivilege>();

        public EditPR()
        {
            InitializeComponent();
        }

        public EditPR(int id)
        {
            InitializeComponent();

            if (id > 0)
            {
                var pri = _sysPrivilege.GetPrivilege(id);
                lbPriID.Text = id.ToString(CultureInfo.InvariantCulture);
                txtPriName.Text = pri.Obj.Privilegename;

                RefreshListBox(id);

            }
        }

        private void RefreshListBox(int id)
        {
            var selectedRoles = GetPriviResources(id).Obj;
            var unselectedRoles = GetPriviUnResources(id).Obj;

            lbSelectedResources.DataSource = selectedRoles.Values.ToList();

            lbUnseletedResources.DataSource = unselectedRoles.Values.ToList();

        }

        /// <summary>
        /// 获取所有资源名称
        /// </summary>
        /// <returns></returns>
        private ResultInfo<Dictionary<string, string>> GetAllResources()
        {
            //var result = new ResultInfo<Dictionary<string, string>>
            //{
            //    ResultNumber = ResultEnum.Error,
            //    Obj = new Dictionary<string, string>()
            //};
            //try
            //{
            //    foreach (var type in GetType().Assembly.GetTypes())
            //    {
            //        if (typeof(Form).IsAssignableFrom(type))
            //        {
            //            try
            //            {
            //                using (var form = Activator.CreateInstance(type) as Form)
            //                {
            //                    if (form != null && !string.IsNullOrEmpty(form.Name))
            //                    {
            //                        result.Obj.Add(form.Name, form.Text);
            //                    }
            //                }
            //            }
            //            catch
            //            {
            //                //throw new DataException();
            //            }
            //        }
            //    }
            //    result.ResultNumber = ResultEnum.Success;
            //}
            //catch (Exception e)
            //{
            //    result.Describe = e.Message;
            //    result.ResultNumber = ResultEnum.Error;
            //}
            //return result;
            return _sysPrivilege.GetAllKeyResources();
        }

        /// <summary>
        /// 获取一个权限没有的资源
        /// </summary>
        /// <param name="priviid"></param>
        /// <returns></returns>
        public ResultInfo<Dictionary<string, string>> GetPriviUnResources(int priviid)
        {
            var result = new ResultInfo<Dictionary<string, string>> { ResultNumber = ResultEnum.Error, Obj = new Dictionary<string, string>() };
            var all = GetAllResources();
            try
            {
                if (all.ResultNumber == ResultEnum.Success)
                {
                    ResultInfo<Privilege> hpris = _sysPrivilege.GetPrivilege(priviid);
                    if (hpris.ResultNumber == ResultEnum.Success)
                    {
                        List<string> hpristr = hpris.Obj.Privilegeresource.Split(',').ToList();
                        foreach (var r in all.Obj)
                        {
                            if (!hpristr.Contains(r.Key))
                            {
                                result.Obj.Add(r.Key, r.Value);
                            }
                        }
                        result.ResultNumber = ResultEnum.Success;
                    }
                    else
                    {
                        result.ResultNumber = ResultEnum.Error;
                        result.Describe = hpris.Describe;
                    }
                }
            }
            catch (Exception)
            {
                result = all;
            }
            return result;
        }

        /// <summary>
        /// 获取权限已经有的资源
        /// </summary>
        /// <param name="priviid"></param>
        /// <returns></returns>
        public ResultInfo<Dictionary<string, string>> GetPriviResources(int priviid)
        {
            var result = new ResultInfo<Dictionary<string, string>> { Obj = new Dictionary<string, string>() };
            try
            {
                ResultInfo<Privilege> pri = _sysPrivilege.GetPrivilege(priviid);
                if (pri.ResultNumber == ResultEnum.Success)
                {
                    string resources = pri.Obj.Privilegeresource;
                    var dicResources = GetAllResources();
                    if (!string.IsNullOrEmpty(resources))
                    {
                        foreach (string resource in resources.Split(','))
                        {

                            if (!string.IsNullOrEmpty(resource) && !result.Obj.Keys.Contains(resource))
                            {
                                string value;
                                dicResources.Obj.TryGetValue(resource, out value);
                                result.Obj.Add(resource, value);
                            }
                        }
                        result.ResultNumber = ResultEnum.Success;
                    }
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = "没有获取到相关资源";
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        private void btnAddPrivilegeResources_Click(object sender, EventArgs e)
        {
            int pid = Convert.ToInt32(lbPriID.Text);
            var item = lbUnseletedResources.SelectedItem;
            var allResources = GetAllResources();
            var resource = allResources.Obj.FirstOrDefault(r => r.Value == item.ToString()).Key;
            if (item != null)
            {
                var pri = _sysPrivilege.GetPrivilege(pid).Obj;

                var sb = new StringBuilder();
                sb.Append(resource + ",");
                pri.Privilegeresource = pri.Privilegeresource + sb;
                _sysPrivilege.CreateUpdatePrivilege(pri);
            }

            RefreshListBox(pid);
        }

        private void btnSubPrivilegeResources_Click(object sender, EventArgs e)
        {
            int pid = Convert.ToInt32(lbPriID.Text);
            var item = lbSelectedResources.SelectedItem;
            var allResources = GetAllResources();
            var resource = allResources.Obj.FirstOrDefault(r => r.Value == item.ToString()).Key;
            if (item != null)
            {
                var pri = _sysPrivilege.GetPrivilege(pid).Obj;
                pri.Privilegeresource = pri.Privilegeresource.Replace(resource, "");
                _sysPrivilege.CreateUpdatePrivilege(pri);
            }

            RefreshListBox(pid);

        }



    }
}
